import WKSDK, { Channel, Message, RecvPacket, SyncOptions } from "wukongimjssdk";
import { getChannelMessagesById } from "../../api";
import Base64 from "base-64";
import utf8 from "utf8";
import { stringToUint8Array } from "../utils";
/**
 * 自定义同步频道消息数据源
 */
export class SyncMessagesTask {
  async start(channel:Channel,opts:SyncOptions): Promise<Message[]> {
    let messages = new Array<Message>();
    try {
      const { data, success } = await getChannelMessagesById({
        channelId: channel.channelID,
        endMessageSeq: opts.endMessageSeq,
        limit: opts.limit,
        // 拉取模式 0:向下拉取 1:向上拉取
        pullMode: opts.pullMode,
        // 开始消息列号，默认值0
        startMessageSeq: opts.startMessageSeq,
        // 当前登录用户uid
        loginUid: WKSDK.shared().config.uid,
      });

      if (success && data.messages) {
        data.messages.map((item: any) => {
          const packet = new RecvPacket();
          packet.channelID = item.channelId;
          packet.channelType = item.channelType;
          packet.fromUID = item.fromUid;
          packet.messageID = item.messageId;
          packet.messageSeq = item.messageSeq;
          packet.timestamp = item.timestamp;
          // 解码
          const payload = Base64.decode(item.payload);
          packet.payload = stringToUint8Array(payload);
          messages.push(new Message(packet));
        });

        return messages;
      }
    } catch (error) {
      console.error("获取频道消息失败", error);
      return messages;
    }
    return messages;
  }
}
